﻿using System;
using System.Diagnostics;
using System.Threading;
using System.Windows.Forms;
using mki.Backup.GUI.Helper;
using mki.Backup.GUI.Properties;
using mki.Backup.Helper;
using mki.Backup.Helper.Extensions;

namespace mki.Backup.GUI
{
	static class Program
	{
		#region Methods (4)

		// Public Static Methods (1) 

		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		public static void Main()
		{
			// set language to systems language
			Thread.CurrentThread.CurrentUICulture = Application.CurrentCulture;

			Application.EnableVisualStyles();
			Application.SetCompatibleTextRenderingDefault(false);
			Application.ThreadException += new ThreadExceptionEventHandler(applicationThreadException);
			AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(currentDomainUnhandledException);

			var mainFormController = new MainFormController();
			Application.Run(mainFormController.MainForm);
		}
		// Private Static Methods (3) 

		/// <summary>
		/// Handles the ThreadException event of the Application control.
		/// </summary>
		/// <param name="sender">The source of the event.</param>
		/// <param name="e">The <see cref="System.Threading.ThreadExceptionEventArgs"/> instance containing the event data.</param>
		private static void applicationThreadException(object sender, ThreadExceptionEventArgs e)
		{
			handleExecption(e.Exception);
		}

		/// <summary>
		/// Handles the UnhandledException event of the CurrentDomain control.
		/// </summary>
		/// <param name="sender">The source of the event.</param>
		/// <param name="e">The <see cref="System.UnhandledExceptionEventArgs"/> instance containing the event data.</param>
		private static void currentDomainUnhandledException(object sender, UnhandledExceptionEventArgs e)
		{
			handleExecption((Exception)e.ExceptionObject);
		}

		/// <summary>
		/// Handles the execption.
		/// </summary>
		/// <param name="ex">The ex.</param>
		private static void handleExecption(Exception ex)
		{
			// get error details
			var trace = new StackTrace(ex, true);
			var errorDetails = String.Empty;

			if (trace.FrameCount > 0 && trace.GetFrame(0) != null && trace.GetFrame(0).GetFileLineNumber() > 0)
			{
				errorDetails = String.Format("at: {0}\n{1} Line {2} Column {3}\n", trace.GetFrame(0).GetFileName(), trace.GetFrame(0).GetMethod().Name, trace.GetFrame(0).GetFileLineNumber(), trace.GetFrame(0).GetFileColumnNumber());
			}

			Logging.WriteCritical("{0}\n{1}\n{2}", ex.GetAllMessages(), ex.StackTrace, errorDetails);
			var errorMessage = String.Format(Resources.ErrorInApplication, ex.Message);

			// finally tell user
			MessageBoxHandler.ShowErrorMessageBox(errorMessage, MessageBoxButtons.OK);
		}

		#endregion Methods
	}
}